package com.postracker.initdatabase.io.csv;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.postracker.initdatabase.io.Table;
import com.postracker.initdatabase.io.TableList;

class TablesFolder implements TableList {
	private File tablesFolder;
	private FileBasedTable tableContentProvider;
	private List<Table> tables = new ArrayList<Table>();
	private File[] filesInFolder;

	public TablesFolder(File tablesFolder, FileBasedTable tableContentProvider) {
		this.tablesFolder = tablesFolder;
		this.tableContentProvider = tableContentProvider;
	}

	private void loadAllFiles() {
		filesInFolder = tablesFolder.listFiles();
		if (emptyFolder()) {
			return;
		}
		for (File file : filesInFolder) {
			loadFile(file);
		}
	}

	private boolean emptyFolder() {
		return filesInFolder == null;
	}

	private void loadFile(File file) {
		tableContentProvider.setFile(file);
		tables.add(tableContentProvider.getTable());
	}

	@Override
	public List<Table> getTables() {
		tables.clear();
		loadAllFiles();
		return tables;
	}

}
